<script setup>
import { ref } from 'vue'
import { loginApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

const ruleFormRef = ref(null)
const formData = ref({
    username: '',
    password: ''
})
const rules = ref({
    name: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 10, message: '姓名并不能为空！', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 1, max: 50, message: '密码不能为空', trigger: 'blur' },
    ],
})
const submitForm = async () => {
    if (!ruleFormRef) return
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            const res = await loginApi(formData.value)
            localStorage.setItem('loginUser', JSON.stringify(res.data))
            if (res.code) {
                ElMessage.success('登录成功！')
                router.push(`/`)
            } else {
                ElMessage.error('登录失败！')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = () => {
    formData.value.resetFields()
}
</script>

<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="formData" :rules="rules" label-width="auto">
        <el-form-item label="请输入账号" prop="username">
            <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="请输入密码" prop="password">
            <el-input v-model="formData.password" />
        </el-form-item>
        <el-form-item>
            <el-button type="success" @click="submitForm()">登录</el-button>
            <el-button type="danger" @click="resetForm()">登出</el-button>
        </el-form-item>
    </el-form>
</template>